<!--公共布局-->
<template>
  <el-container class="layout-container">
    <el-header class="layout-header-b">
      <div class="logo" :class="[isCollapse ? 'logo-is-active' : '']"></div>
      <span
        @click="toggleAside()"
        :class="['icon', 'el-icon-s-fold', isCollapse ? 'collapsed' : '']"
      ></span>
      <span class="text">
        <i class="breadText" v-if="$route.name === '首页'">{{$t("common.home")}}</i>
        <my-bread v-else-if="$route.name !== '首页'"></my-bread>
      </span>
      <!-- 下拉菜单组件 -->
      <el-dropdown class="my-dropdown" @command="clickItem">
        <span class="el-dropdown-link">
          <img class="avatar" :src="photo" alt />
          <span class="name">{{name}}</span>
          <i class="el-icon-arrow-down el-icon--right"></i>
        </span>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item icon="el-icon-unlock" command="logout">{{$t("common.logout")}}</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <!-- 语言切换组件 -->
      <div class="language">
        <!-- 语言切换 -->
        <li class="el-icon-s-tools lang-selector" v-popover:popover-lang>{{this.$i18n.locale}}</li>
        <el-popover
          id="langPopover"
          ref="popover-lang"
          placement="bottom-start"
          trigger="click"
          v-model="langVisible"
        >
          <div class="lang-item" @click="changeLanguage('简体中文')">简体中文</div>
          <div class="lang-item" @click="changeLanguage('English')">English</div>
        </el-popover>
        <!-- 欢迎登陆,{{currUserInfo.userDesc}} -->
      </div>
    </el-header>
    <el-container class="layout-container-b">
      <el-aside :width="isCollapse?'64px':'240px'">
        <el-menu
          :default-active="$route.path"
          class="el-menu-vertical-demo"
          background-color="#fff"
          text-color="#000"
          :collapse="isCollapse"
          :collapse-transition="false"
          router
        >
          <el-menu-item index="/">
            <i class="el-icon-s-home"></i>
            <span>{{$t('common.home')}}</span>
          </el-menu-item>
          <el-submenu index="/sys">
            <template slot="title">
              <i class="el-icon-s-tools"></i>
              <span slot="title">{{$t('sys.sysMng')}}</span>
            </template>
            <el-menu-item-group>
              <el-menu-item index="/sys/user">
                <i class="el-icon-user-solid"></i>
                <span>{{$t('sys.EmpMng')}}</span>
              </el-menu-item>
              <el-menu-item index="/sys/role">
                <i class="el-icon-view"></i>
                {{$t('sys.roleMng')}}
              </el-menu-item>
              <el-menu-item index="/sys/auth">
                <i class="el-icon-menu"></i>
                {{$t('sys.authMng')}}
              </el-menu-item>
              <el-menu-item index="/sys/dict">
                <i class="el-icon-notebook-1"></i>
                {{swichLang('dataDta')}}
              </el-menu-item>
            </el-menu-item-group>
          </el-submenu>
        </el-menu>
      </el-aside>
      <el-main>
        <!-- 标签页 -->
        <div class="tab-container" :class="[isCollapse ? 'tabs-is-active' : '']">
          <el-tabs
            ref="tabs"
            class="tabs"
            :class="$store.state.app.collapse?'position-collapse-left':'position-left'"
            v-model="mainTabsActiveName"
            type="card"
            @tab-click="selectedTabHandle"
            @tab-remove="removeTabHandle"
          >
            <el-dropdown class="tabs-tools" :show-timeout="0" trigger="hover">
              <div style="font-size:20px;width:50px;">
                <i class="el-icon-arrow-down"></i>
              </div>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item @click.native="tabsCloseCurrentHandle">关闭当前标签</el-dropdown-item>
                <el-dropdown-item @click.native="tabsCloseOtherHandle">关闭其它标签</el-dropdown-item>
                <el-dropdown-item @click.native="tabsCloseAllHandle">关闭全部标签</el-dropdown-item>
                <el-dropdown-item @click.native="tabsRefreshCurrentHandle">刷新当前标签</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <el-tab-pane
              v-for="item in mainTabs"
              :key="item.name"
              :label="item.title"
              :name="item.name"
              :closable="item.close"
            >
              <span slot="label">
                <i :class="item.icon"></i>
                <i v-if="$store.state.app.local === 'English'">{{item.enName}}</i>
                <i v-else>{{item.title}}</i>
              </span>
            </el-tab-pane>
          </el-tabs>
        </div>
        <div class="layout-main" :class="[isCollapse ? 'main-is-active' : '']">
          <router-view />
          <!-- <keep-alive :include="keepAliveList">
            <router-view :key="$route.fullPath" />
          </keep-alive>-->
        </div>
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
import store from '../store/index'
import Language from './common/Language/language'
import jwtDecode from 'jwt-decode'
import { mapMutations } from 'vuex'
import { mapState } from 'vuex'
import { swichLang, setTabs } from '../utils/auth'
import { logout, reFreshToken } from '../api/modules/login'
// import jwtDecode from 'jwt-decode'
import axios from 'axios'

export default {
  components: {
    Language
  },
  data () {
    return {
      isCollapse: store.state.app.collapse,
      name: '',
      photo: '',
      headers: { Authorization: '' },
      activeIndex: '1',
      langVisible: false,
      currUserInfo: {},
      timer: null,
      firstTime: ''
    }
  },
  created () {
    const user = store.state.app.user
    this.headers.Authorization = store.getters.token()
    this.handleRoute(this.$route)
    this.timer = setInterval(() => {
      reFreshToken().then((res) => {
        if (res.code === '401') {
          this.delToken()
        } else {
          this.delToken()
          this.setToken(res)
        }
      })
    }, 690000)
    // const userToken = jwtDecode(user.token)
    // sub: "admin"
    // exp: 1576612786
    // iat: 1576612066
    // this.name = userToken.sub
    // this.photo = user.photo
    // this.filterUserByUserName()
  },
  computed: {
    ...mapState({
      collapse: state => state.app.collapse,
      navTree: state => state.app.navTree,
      keepAliveList: state => state.app.keepAliveList
    }),
    mainTabs: {
      get () { return this.$store.state.app.mainTabs },
      set (val) { this.$store.commit('updateMainTabs', val) }
    },
    mainTabsActiveName: {
      get () { return this.$store.state.app.mainTabsActiveName },
      set (val) { this.$store.commit('updateMainTabsActiveName', val) }
    },
    local () {
      return this.$store.state.app.local
    }
  },
  watch: {
    $route: 'handleRoute'
  },
  methods: {
    ...mapMutations(['delToken', 'setToken', 'setLocal', 'setLang', 'delTabs', 'setUserInfo', 'getUserInfo']),
    filterUserByUserName (name) {
      this.currUserInfo = this.$store.getters.userInfo
      this.$api.emplotee.findEmployByUserName(this.currUserInfo.userName).then(res => {
        if (res.code === '200') {
          this.currUserInfo = res.obj;
          this.setUserInfo(res.obj);
          // this.downloadAvatar()
        }
      })
    },
    // async downloadAvatar () {
    //   this.baseUrlTow = '/system/user/download/avatar/'
    //   let url = process.env.BASE_API + this.baseUrlTow + this.currUserInfo.id
    //   axios({
    //     method: 'get',
    //     url: url,
    //     headers: { Authorization: this.headers.Authorization },
    //     // responseType: 'arraybuffer'
    //   }).then(res => {
    //     if (res.data.code === '200') {
    //       let src = 'data:image/jpg;base64,' + res.data.obj
    //       this.photo = src
    //     }
    //   })
    // },
    clickItem (command) {
      this[command]()
    },
    setting () {
      this.$router.push('/setting')
    },
    // 退出登录
    logout () {
      // this.$api.login.logout().then().catch()
      let that = this;
      logout().then((res) => {
        // if (res.code === '200') {
        that.delToken()
        that.delTabs()
        // 保存加载状态
        that.$store.commit('menuRouteLoaded', false)
        // 保存菜单树
        that.$store.commit('setNavTree', {})
        that.tabsCloseAllHandle()
        // that.$router.push('/login').catch((e)=>{})
        // }
      }).catch((err) => {
      })
    },
    toggleAside () {
      this.isCollapse = !this.isCollapse
      this.$store.commit('onCollapse')
    },
    // tabs, 选中tab
    selectedTabHandle (tab) {
      tab = this.mainTabs.filter(item => item.name === tab.name)
      if (tab.length >= 1) {
        this.$router.push({ name: tab[0].name })
      }
    },
    // tabs, 删除tab
    removeTabHandle (tabName) {
      if (this.mainTabs.length <= 1) {
        return
      }
      this.deleteKeepAlive(tabName)
      this.mainTabs = this.mainTabs.filter(item => item.name !== tabName)
      if (this.mainTabs.length >= 1) {
        // 当前选中tab被删除
        if (tabName === this.mainTabsActiveName) {
          this.$router.push({ name: this.mainTabs[this.mainTabs.length - 1].name }, () => {
            this.mainTabsActiveName = this.$route.name
          })
        }
      } else {
        this.$router.push('/')
      }
    },
    deleteKeepAlive (tabName) {
      let arr = this.$router.options.routes[0].children.filter(o => o.name === tabName)
      let path = arr[0].path.split('/')
      let code = path[path.length - 1]
      let keepArr = this.keepAliveList.split(',')
      keepArr.splice(keepArr.indexOf(code), 1)
      store.commit('setKeepAliveList', keepArr.join())
    },
    // tabs, 关闭当前
    tabsCloseCurrentHandle () {
      this.removeTabHandle(this.mainTabsActiveName)
    },
    // tabs, 关闭其它
    tabsCloseOtherHandle () {
      this.mainTabs = this.mainTabs.filter(item => item.name === this.mainTabsActiveName)
      if (this.mainTabs[0].code !== 'home') {
        this.mainTabs.unshift({
          name: '首页',
          title: '首页',
          icon: 'el-icon-s-home',
          code: 'home',
          close: false
        })
      }
      setTabs(this.mainTabs)
    },
    // tabs, 关闭全部
    tabsCloseAllHandle () {
      this.mainTabs = [{
        name: '首页',
        title: '首页',
        enName: 'Home',
        code: 'home',
        icon: 'el-icon-s-home',
        close: false
      }]
      this.$router.push('/login')//此处有多次路径切换,会报错,catch后不抛出异常
    },
    // tabs, 刷新当前
    tabsRefreshCurrentHandle () {
      let arr = this.$router.options.routes[0].children.filter(o => o.name === this.mainTabsActiveName)
      let path = arr[0].path.split('/')
      let code = path[path.length - 1]
      this.resetKeepAive(code, this.keepAliveList) // 删除缓存路由
      this.$nextTick(() => {
        this.$router.replace({
          path: '/refresh',
          query: {
            t: Date.now()
          }
        })
      })
    },
    // 更新要缓存的路由列表
    resetKeepAive (name, cacheList) {
      const conf = this.keepAliveList;
      let arr = cacheList.split(',');
      if (name && typeof name === 'string') {
        let i = arr.indexOf(name);
        if (i > -1) {
          arr.splice(i, 1)
          this.$store.commit('setKeepAliveList', arr.join())
          this.$nextTick(() => { //添加缓存路由
            this.$store.commit('setKeepAliveList', conf)
          })
        }
      }
    },
    // 路由操作处理
    handleRoute (route) {
      if (route.name === '刷新') {
        return
      }
      if (Array.isArray(this.mainTabs)) {
        var tab = this.mainTabs.filter(item => item.name === route.name)[0]
      } else {
        this.mainTabs = []
      }
      // tab标签页选中, 如果不存在则先添加
      if (!tab) {
        tab = {
          name: route.name,
          enName: route.meta.enName,
          title: route.name,
          icon: route.meta.icon,
          code: route.meta.code,
          close: route.meta.close
        }
        this.mainTabs = this.mainTabs.concat(tab)
      }
      this.mainTabsActiveName = tab.name
      // 切换标签页时同步更新高亮菜单
      this.$nextTick(() => {
        if (this.$refs.navmenu) {
          this.$refs.navmenu.activeIndex = '' + route.meta.index
          this.$refs.navmenu.initOpenedMenu()
        }
      })
    },
    // 语言切换
    changeLanguage (lang) {
      lang === '' ? '简体中文' : lang
      this.setLocal(lang)
      this.$i18n.locale = lang
      this.langVisible = false
    },
    swichLang,
    handleClick (e) {
      const now = Math.round(new Date().getTime() / 1000)
      if (now - this.firstTime >= 1800) {
        this.delTabs()
        this.delToken()
        this.$router.push({ path: '/login' })
        return
      }
      this.firstTime = now
      const userToken = window.sessionStorage.getItem('evst-platform-token')
      const token = jwtDecode(userToken)
      const time = token.exp - now
      if (time <= 60) {
        reFreshToken().then((res) => {
          if (res.code === '401') {
            this.delToken()
          } else {
            this.delToken()
            this.setToken(res)
          }
        })
      }
    },
    handleKeyup (e) {
      const now = Math.round(new Date().getTime() / 1000)
      if (now - this.firstTime >= 1800) {
        this.delTabs()
        this.delToken()
        this.$router.push({ path: '/login' })
        return
      }
      this.firstTime = now
      const userToken = window.sessionStorage.getItem('evst-platform-token')
      const token = jwtDecode(userToken)
      const time = token.exp - now
      if (time <= 60) {
        reFreshToken().then((res) => {
          if (res.code === '401') {
            this.delToken()
          } else {
            this.delToken()
            this.setToken(res)
          }
        })
      }
    },
    handleScroll (e) {
      const now = Math.round(new Date().getTime() / 1000)
      if (now - this.firstTime >= 1800) {
        this.delTabs()
        this.delToken()
        this.$router.push({ path: '/login' })
        return
      }
      this.firstTime = now
      const userToken = window.sessionStorage.getItem('evst-platform-token')
      const token = jwtDecode(userToken)
      const time = token.exp - now
      if (time <= 60) {
        reFreshToken().then((res) => {
          if (res.code === '401') {
            this.delToken()
          } else {
            this.delToken()
            this.setToken(res)
          }
        })
      }
    }
  },
  mounted () {
    this.filterUserByUserName();
    this.setLocal(this.$i18n.locale)
    swichLang()
    this.firstTime = Math.round(new Date().getTime() / 1000)
    window.addEventListener('keyup', this.handleKeyup)
    window.addEventListener('click', this.handleClick)
    window.addEventListener('scroll', this.handleScroll)
  },
  destroyed () {
    clearInterval(this.timer)
    this.timer = null
    window.removeEventListener('keyup', this.handleKeyup)
    window.removeEventListener('click', this.handleClick)
    window.removeEventListener('scroll', this.handleScroll)
  },
  beforeDestroy () {
    clearInterval(this.timer)
    this.timer = null
  }
}
</script>

<style scoped lang='scss'>
.layout-container {
  width: 100%;
  height: 100%;
  position: absolute;
  left: 0;
  top: 0;
  display: flex;
  .layout-container-b {
    .el-aside {
      height: calc(100vh - 60px) !important;
      &::-webkit-scrollbar {
        width: 2px;
        height: 10px;
      }

      &::-webkit-scrollbar-thumb {
        border-radius: 6px;
        background: #dbdcdc;
      }
      border-right: 1px #ddd solid;
      background-color: #fff;

      .logo {
        width: 100%;
        height: 60px;
        background-color: #333;
      }
      // logo 后面 覆盖之前的样式
      .miniLogo {
        background-size: 36px auto;
      }
    }
  }

  .el-main {
    padding: 0;
    flex: 1;
    // position: absolute;
    .layout-main {
      /*height: 100%;*/
      padding: 20px;
    }
  }
}

.position-left {
  left: 200px;
}

.position-collapse-left {
  left: 65px;
}

.language {
  color: #fff;
}
</style>
